import mongoose from 'mongoose';
import md5 from 'crypto-js/md5';

export interface IUser extends mongoose.Document {
    userId: string;
    username: string;
    email: string;
    password: string;
    avatar: string;
    age: number;
    phone: string;
    address: string;
    systemRole: string;
    status: string;
    createdAt: Date;
    updatedAt: Date;
    comparePassword(candidatePassword: string): Promise<boolean>;
}

const userSchema = new mongoose.Schema({
    userId: {
        type: String,
        required: true,
        unique: true
    },
    username: {
        type: String,
        required: true,
        unique: true,
        trim: true,
    },
    avatar: {
        type: String,
        default: '',
    },
    email: {
        type: String,
        required: true,
        unique: true,
        trim: true,
        lowercase: true,
    },
    phone: {
        type: String,
        required: true,
        unique: true,
        trim: true,
    },
    age: {
        type: Number,
        default: 0,
    },
    address: {
        type: String,
        default: '',
    },
    password: {
        type: String,
        required: true,
    },
    systemRole: {
        type: String,
        default: 'user',
        enum: ['user', 'admin', 'superAdmin'],
    },
    status: {
        type: String,
        default: 'active',
        enum: ['active', 'inactive'],
    },
}, {
    timestamps: true,
});

// 密码加密中间件
userSchema.pre('save', async function (next) {
    if (!this.isModified('password')) return next();

    try {
        this.password = md5(this.password).toString();
        next();
    } catch (error: any) {
        next(error);
    }
});

// 密码比较方法
userSchema.methods.comparePassword = async function (candidatePassword: string): Promise<boolean> {
    return candidatePassword === this.password;
};

export const User = mongoose.model<IUser>('User', userSchema);